package com.kim.smartring.activity.fragment;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.kim.smartring.R;
import com.kim.smartring.adapter.DevicesBindingAdapter;
import com.kim.smartring.ble.BleWrapper;
import com.kim.smartring.ble.BleWrapperUiCallbacks;
import com.kim.smartring.interfaces.DeviceBindingCallback;
import com.kim.smartring.utils.ConfigUtils;

public class BindFragment extends BaseFragment implements OnItemClickListener,
		DeviceBindingCallback {

	private static final String TAG = "BindFragment";

	private static final long SCANNING_TIMEOUT = 10 * 1000l; // 设备搜索超时时间 10秒钟
	private static final int ENABLE_BT_REQUEST_ID = 1; //

	private boolean mScanning = false;
	private BleWrapper mBleWrapper = null;
	private DevicesBindingAdapter mDevicesAdapter;

	private ImageView img_menu;
	private Button btn_bind;// 绑定
	private TextView txv_device;// 绑定的设备名

	private ProgressBar progressBar;

	private ListView mDevicesListView;

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
		}

	};

	public BindFragment() {

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.bind_layout, null);
		initView(v);
		return v;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		// create BleWrapper with empty callback object except uiDeficeFound
		// function (we need only that here)
		mBleWrapper = new BleWrapper(getActivity(),
				new BleWrapperUiCallbacks.Null() {
					@Override
					public void uiDeviceFound(final BluetoothDevice device,
							final int rssi, final byte[] record) {
						handleFoundDevice(device, rssi, record);
					}
				});

		// check if we have BT and BLE on board
		if (mBleWrapper.checkBleHardwareAvailable() == false) {
			bleMissing();
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		showBindState();

		// on every Resume check if BT is enabled (user could turn it off while
		// app was in background etc.)
		if (mBleWrapper.isBtEnabled() == false) {
			// BT is not turned on - ask user to make it enabled
			Intent enableBtIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableBtIntent, ENABLE_BT_REQUEST_ID);
			// see onActivityResult to check what is the status of our request
		}

		// initialize BleWrapper object
		mBleWrapper.initialize();

		mDevicesAdapter = new DevicesBindingAdapter(getActivity(), this);
		mDevicesListView.setAdapter(mDevicesAdapter);

		// Automatically start scanning for devices
		mScanning = true;
		// remember to add timeout for scanning to not run it forever and drain
		// the battery
		addScanningTimeout();
		mBleWrapper.startScanning();

		invalidateScanBtnState();
	}

	@Override
	public void onPause() {
		super.onPause();
		mScanning = false;
		mBleWrapper.stopScanning();
		mDevicesAdapter.clearList();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// user didn't want to turn on BT
		if (requestCode == ENABLE_BT_REQUEST_ID) {
			if (resultCode == Activity.RESULT_CANCELED) {
				btDisabled();
				return;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);

	}

	public void initView(View v) {

		img_menu = (ImageView) v.findViewById(R.id.img_menu);
		btn_bind = (Button) v.findViewById(R.id.btn_bind);
		txv_device = (TextView) v.findViewById(R.id.txv_device);

		mDevicesListView = (ListView) v.findViewById(R.id.lv_devices);

		progressBar = (ProgressBar) v.findViewById(R.id.pb_scanstate);

		mDevicesListView.setOnItemClickListener(this);
		img_menu.setOnClickListener(this);
		btn_bind.setOnClickListener(this);

	}

	@Override
	public void onClick(View arg0) {

		switch (arg0.getId()) {
		case R.id.img_menu:
			showSlidingMenu();
			break;
		case R.id.btn_bind:
			if (mBleWrapper.isBtEnabled() == false) {
				// BT is not turned on - ask user to make it enabled
				Intent enableBtIntent = new Intent(
						BluetoothAdapter.ACTION_REQUEST_ENABLE);
				startActivityForResult(enableBtIntent, ENABLE_BT_REQUEST_ID);
				// see onActivityResult to check what is the status of our
				// request
			}
			if (mScanning) {
				mScanning = false;
				mBleWrapper.stopScanning();
			} else {
				mScanning = true;
				mBleWrapper.startScanning();
			}
			invalidateScanBtnState();
			addScanningTimeout();
			break;

		default:
			break;
		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {

	}

	@Override
	public void onBind(boolean isBinded) {
		showBindState();
	}

	/**
	 * 显示设备绑定状态
	 */
	private void showBindState() {
		if (ConfigUtils.isDeviceBinded()) {
			txv_device.setText("你已绑定设备：" + ConfigUtils.getBindedDeviceName());
		} else {
			txv_device.setText("快绑定你的设备吧");
		}
	}

	private void bleMissing() {
		Toast.makeText(getActivity(),
				"BLE Hardware is required but not available!",
				Toast.LENGTH_LONG).show();
	}

	private void btDisabled() {
		Toast.makeText(getActivity(),
				"Sorry, BT has to be turned ON for us to work!",
				Toast.LENGTH_LONG).show();
	}

	/* add device to the current list of devices */
	private void handleFoundDevice(final BluetoothDevice device,
			final int rssi, final byte[] scanRecord) {
		// adding to the UI have to happen in UI thread
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				mDevicesAdapter.addDevice(device, rssi, scanRecord);
				mDevicesAdapter.notifyDataSetChanged();
			}
		}, 100);
	}

	private void invalidateScanBtnState() {
		if (mScanning) {
			btn_bind.setText("停止扫描周边设备");
			progressBar.setVisibility(View.VISIBLE);
		} else {
			btn_bind.setText("开始绑定设备");
			progressBar.setVisibility(View.GONE);
		}
	}

	/*
	 * make sure that potential scanning will take no longer than
	 * <SCANNING_TIMEOUT> seconds from now on
	 */
	private void addScanningTimeout() {
		Runnable timeout = new Runnable() {
			@Override
			public void run() {
				if (mBleWrapper == null)
					return;
				mScanning = false;
				mBleWrapper.stopScanning();
				invalidateScanBtnState();
			}
		};
		handler.postDelayed(timeout, SCANNING_TIMEOUT);
	}

}